import React, { PureComponent } from 'react'
import Cover from '@/components/Cover'
import Swiper from './swiper'
import LoadMore from '@/components/LoadMore'
import { indexApi } from '@/api'
export default class Index extends PureComponent {
    listRef = React.createRef()
    state = {
        swipes: [],
        list: [],
        currentPage: 1,
        pageSize: 10,
        totalPage: 0
    }

    componentDidMount() {
        this.getSwipes()
        this.getList()
    }
    // 获取轮播图数据
    getSwipes = async () => {
        try {
            const { data } = await indexApi.getSwipe()
            if (Array.isArray(data)) {
                this.setState({
                    swipes: data
                })
            }
        } catch (error) {
            console.log(error)
        }
    }

    getList = async () => {
        try {
            const { data } = await indexApi.getRecommand()
            if (!data) {
                return
            }            
            const { list } = data
            if (!Array.isArray(list)) {
                this.complete()
                return
            }
            const { pageSize } = this.state
            this.setState({
                list,
                totalPage: Math.ceil(list.length / pageSize)
            })        
        } catch (error) {
            console.log(error)
        } finally {
            this.stopRefresh()
        }        
    }

    stopRefresh = () => {
        this.listRef?.current?.stopRefresh()
    }
    complete = () => {
        this.listRef?.current?.complete()
    }
    onRefresh = async () => {
        this.setState({
            currentPage: 1
        }, () => {
            this.getList()
        })
    }
    onReachEnd = () => {
        const { currentPage, totalPage } = this.state        
        if (currentPage < totalPage) {
            const nextPage = currentPage + 1
            this.setState({
                currentPage: nextPage
            })
        } else {
            this.complete()
        }
    }
    
    onRender = (rowData, sectionID, rowId) => {
        return (
            <Cover key={rowData.bvid} {...rowData} play={rowData.play || rowData.stat.view } danmaku={rowData.video_review || rowData.stat.danmaku}  />
        )
    }
    
    render() {
        const { swipes, list, currentPage, pageSize } = this.state
        const pageList = list.slice(0, currentPage * pageSize)
        return (
            <>
                <Swiper data={swipes} />
                <LoadMore                    
                    ref={this.listRef}
                    data={pageList} 
                    column={2}
                    onRefresh={this.onRefresh} 
                    onReachEnd={this.onReachEnd} 
                    renderRow={this.onRender}
                />
            </>
        )
    }
}
